import 'package:cmd_myapp_demo/components/my_app.dart';
import 'package:cmd_myapp_demo/components/my_home_page.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp(child: _TweenDemo()));
}

class _TweenDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MyHomePage(title: const Text("Tween 补间动画"), child: _TweenAnimationPage());
  }
}

class _TweenAnimationPage extends StatefulWidget {
  @override
  _TweenAnimationPageState createState() => _TweenAnimationPageState();
}

class _TweenAnimationPageState extends State<_TweenAnimationPage> with SingleTickerProviderStateMixin {

  late Animation<double> animation;
  late AnimationController controller;
  double animationValue = 0.0;

  @override
  void initState() {
    super.initState();
    // 初始化动画控制器
    controller = AnimationController(
      // 动画时长
      duration: const Duration(milliseconds: 2000),
      vsync: this
    );
    // 初始化动画,并用 Tween 设置范围
    // 添加2个监听器
    animation = Tween(begin: 10.0, end: 300.0).animate(controller);

    // 添加监听器
    animation.addListener(() {
      // 什么也不做
      setState(() {
        animationValue = animation.value;
      });
    });

    // 添加状态监听器
    animation.addStatusListener((status) {
      // 实现动画循环播放
      if (status == AnimationStatus.completed) {
        controller.reverse();
      } else if (status == AnimationStatus.dismissed) {
        controller.forward();
      }
    });

    // 开始动画
    controller.forward();
  }

  @override
  void dispose() {
    // 销毁
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        height: animationValue,
        width: animationValue,
        color: Colors.blue,
      ),
    );
  }
}